import axios from "axios";
import QS from "qs";
import { ResponseCode, ResponseError } from "./response-code";
import { useUserStore } from "@/store/modules/user";

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: import.meta.env.VITE_APP_BASE_API,
  withCredentials: true, // send cookies when cross-domain requests
  // 超时
  timeout: 60000
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    const userStore = useUserStore();
    const token = userStore.token;
    if (token) {
      config.headers["authorize"] = token;
    }
    // get请求
    if (config.params) {
      config.url += "?" + QS.stringify(config.params, { indices: false });
      config.params = {};
    } else if (config.data && config.json === false) {
      //post参数非json格式
      config.data = QS.stringify(config.data, { indices: false });
    } else {
      // 否则默认json格式
      config.headers["Content-Type"] = "application/json;charset=utf-8";
    }

    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (response.headers["content-type"] === "application/x-download" || res instanceof Blob) {
      return response;
    } else if (res.code && res.code !== 200) {
      // 不等于200,后台返回的code
      ResponseCode(res);
      return Promise.reject(res);
    } else {
      return res;
    }
  },
  (error) => {
    ResponseError(error);
    return Promise.reject();
  }
);

export default service;
